package person.twj.session.core.security;

import jakarta.servlet.*;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.DefaultRedirectStrategy;
import org.springframework.security.web.RedirectStrategy;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import org.springframework.security.web.util.matcher.RequestMatcher;

import java.io.IOException;

public class WelcomeFilter implements Filter {

    private final String loginPageUrl;
    private RequestMatcher requiresAuthenticationRequestMatcher ;
    private RedirectStrategy redirectStrategy;

    public WelcomeFilter(String filterProcessesUrl,String loginPageUrl) {
        this.loginPageUrl = loginPageUrl;
        this.requiresAuthenticationRequestMatcher = new AntPathRequestMatcher(filterProcessesUrl);
        this.redirectStrategy = new DefaultRedirectStrategy();
    }
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws ServletException, IOException {
        doFilter((HttpServletRequest) request, (HttpServletResponse) response, chain);
    }

    public void doFilter(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {
        //过滤路径，只接收 filterProcessesUrl 路径的
        if (!requiresAuthentication(request, response)) {
            chain.doFilter(request,response);
            return;
        }
        if (!request.getMethod().equals("GET")) {
            throw new AuthenticationServiceException("Authentication method not supported: " + request.getMethod());
        }
        // 判断是否需要登录
        // 1. 存在身份信息 2. 身份信息已认证
        if(SecurityContextHolder.getContext().getAuthentication()!=null&&SecurityContextHolder.getContext().getAuthentication().isAuthenticated()){
            //已经认证，不需要登录
            chain.doFilter(request,response);
            return;
        }else{
            //没有认证，重定向/login页面
            getRedirectStrategy().sendRedirect(request, response, this.loginPageUrl);
        }


    }


    private RedirectStrategy getRedirectStrategy() {
        return this.redirectStrategy;
    }


    protected boolean requiresAuthentication(HttpServletRequest request, HttpServletResponse response) {
        if (this.requiresAuthenticationRequestMatcher.matches(request)) {
            return true;
        }

        return false;
    }
}
